import CryptoJS from 'crypto-js/crypto-js'
const sys = {
	//baseUrl: 'http://125.74.7.54:80/YdjyBeianServer/',
	baseUrl: 'http://61.52.78.173:8880/YdjyBeianServer/',
	key: 'zhengch_hdsm!~@#^&()^%TR%$',
	toSSOLogin:true,
	ssoUrl:'https://zwfw.gansu.gov.cn/gsjis/natural/newJAdByContryMobile?LinkAddr',
	appid:'ydjyzxbl',
	appkey:'akb9vlUvj8MyBM2m',
	redirectUri:'http://localhost:8080/yidijiuyi_h5?a=1',

	IV: CryptoJS.enc.Utf8.parse("1234567890123456")

}
//把obj对象里的值覆盖到newobj里面
function deepCopy(newobj, obj) {
	if (typeof obj != 'object') {
		return obj;
	}
	for (var attr in obj) {
		var a = {};
		if (newobj[attr]) {
			a = newobj[attr];
		}
		newobj[attr] = deepCopy(a, obj[attr]);
	}
	return newobj;
}

function getDate(targetDate) {
	var D, y, m, d;
	if (targetDate) {
		D = new Date(targetDate);
		y = D.getFullYear();
		m = D.getMonth() + 1;
		d = D.getDate();
	} else {
		y = fullYear;
		m = month;
		d = date;
	}
	m = m > 9 ? m : '0' + m;
	d = d > 9 ? d : '0' + d;
	return y + '-' + m + '-' + d;

}

/**
 * AES加密 ：字符串 key iv  返回base64 
 */
function Encrypt(word) {
	let key = sys.IV
	let iv = sys.IV
	let srcs = CryptoJS.enc.Utf8.parse(word);
	var encrypted = CryptoJS.AES.encrypt(srcs, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	});
	// console.log("-=-=-=-", encrypted.ciphertext)
	return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

}
//AES 解密 ：字符串 key iv  返回base64 
function Decrypt(word) {
	try {
		var vals = word;
		    var options = {
		        mode: CryptoJS.mode.ECB,
		        padding: CryptoJS.pad.Pkcs7
		    };
		    var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");
		    var decryptedData = CryptoJS.AES.decrypt(vals, key, options);
		    var decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);
		    return decryptedStr

	} catch (ex) {
		console.log(ex);
		return word;
	}
}


//当出错的时候，显示错误信息，并且跳转 弃用
/* function errorToBack(msg = '出错了，请重试',delta=1){
  uni.showToast({
    title: msg,
    icon: 'none',
    duration: 2000,
  });
  if(delta > 0){
    setTimeout(function () {
      uni.navigateBack({
        delta: delta
      })
    }, 1000);
  }
} */
//操作成功后，的提示信息
function successToShow(msg = '保存成功', callback = function() {}) {

	setTimeout(function() {
		uni.showToast({
			title: msg,
			icon: 'success',
			duration: 2000,
		});
		callback();
	}, 2000);
}


//操作失败的提示信息
function errorToShow(msg = '操作失败', callback = function() {}) {
	setTimeout(function() {
		uni.showToast({
			title: msg,
			icon: 'none',
			duration: 2000,
		});
		callback();
	}, 50);
}

//加载显示
function loadToShow(msg = '加载中') {
	uni.showToast({
		title: msg,
		icon: 'loading',
	});
}

//加载隐藏
function loadToHide() {
	uni.hideToast();
}

// 提示框
function modelShow(title = '提示', content = '确认执行此操作吗?', callback = () => {}, showCancel = true, cancelText = '取消',
	confirmText = '确定') {
	uni.showModal({
		title: title,
		content: content,
		showCancel: showCancel,
		cancelText: cancelText,
		confirmText: confirmText,
		cancelText: cancelText,
		success: function(res) {
			if (res.confirm) {
				// 用户点击确定操作
				setTimeout(() => {
					callback()
				}, 500)
			} else if (res.cancel) {
				// 用户取消操作
			}
		}
	});
}


//时间戳转时间格式
function timeToDate(date) {
	var date = new Date(date * 1000); //如果date为13位不需要乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return Y + M + D + h + m + s;
}

function time2date(micro_second) {
	var time = {};
	// 总秒数
	var second = Math.floor(micro_second);
	// 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2);
	// 小时
	time.hour = PrefixInteger(Math.floor(second / 3600 % 24), 2);
	// 分钟
	time.minute = PrefixInteger(Math.floor(second / 60 % 60), 2);
	// 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2);

	var newtime = '';
	if (time.day > 0) {
		newtime = time.day + '天' + time.hour + '小时' + time.minute + '分' + time.second + '秒';
	} else {
		if (time.hour != 0) {
			newtime = time.hour + '小时' + time.minute + '分' + time.second + '秒';
		} else {
			newtime = time.minute + '分' + time.second + '秒';
		}
	}
	return newtime;
}

//货币格式化
function formatMoney(number, places, symbol, thousand, decimal) {
	number = number || 0;
	places = !isNaN(places = Math.abs(places)) ? places : 2;
	symbol = symbol !== undefined ? symbol : "￥";
	thousand = thousand || ",";
	decimal = decimal || ".";
	var negative = number < 0 ? "-" : "",
		i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
		j = (j = i.length) > 3 ? j % 3 : 0;
	return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" +
		thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

function throttle(fn, context, delay) {
	clearTimeout(fn.timeoutId);
	fn.timeoutId = setTimeout(function() {
		fn.call(context);
	}, delay);
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
	var time = {};
	// 总秒数
	var second = Math.floor(micro_second / 1000);
	// 天数
	time.day = PrefixInteger(Math.floor(second / 3600 / 24), 2);
	// 小时
	time.hour = PrefixInteger(Math.floor(second / 3600 % 24), 2);
	// 分钟
	time.minute = PrefixInteger(Math.floor(second / 60 % 60), 2);
	// 秒
	time.second = PrefixInteger(Math.floor(second % 60), 2);
	return time;
}


//不足位数前面补0
function PrefixInteger(num, length) {
	return (Array(length).join('0') + num).slice(-length);
}

//验证是否是手机号
function isPhoneNumber(str) {
	var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
	if (!myreg.test(str)) {
		return false;
	} else {
		return true;
	}
}

// 验证中国大陆身份证号
function isIdCardNumber(str) {
	var idcardReg =
		/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
	if (!idcardReg.test(str)) {
		return false;
	} else {
		return true;
	}
}



/**
 * 
 * 对象参数转为url参数
 * 
 */
function builderUrlParams(url, data) {
	if (typeof(url) == 'undefined' || url == null || url == '') {
		return '';
	}
	if (typeof(data) == 'undefined' || data == null || typeof(data) != 'object') {
		return '';
	}
	url += (url.indexOf("?") != -1) ? "" : "?";
	for (var k in data) {
		url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(data[k]);
	}
	return url;
}

/**
 * 使用循环的方式判断一个元素是否存在于一个数组中
 * @param {Object} arr 数组
 * @param {Object} value 元素值
 */
function isInArray(arr, value) {
	for (var i = 0; i < arr.length; i++) {
		if (value === arr[i]) {
			return true;
		}
	}
	return false;
}
/**
 * 统一跳转
 */
function navigateTo(url) {
	uni.navigateTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	});
}


/**
 *  关闭当前页面并跳转
 */
function redirectTo(url) {
	uni.redirectTo({
		url: url,
		animationType: 'pop-in',
		animationDuration: 300
	})
}


/**
 * 
 *  判断是否在微信浏览器 true是
 */
function isWeiXinBrowser() {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	// #endif

	// #ifdef MP
	return false;
	// #endif
}

//app压缩图片  用for循环 来处理图片压缩 的问题，原因是 plus.zip.compressImage 方法 是异步执行的，for循环很快， 同时手机可执行的压缩方法有限制：应该是3个吧。超出直接就不执行了。所以 原理就是 在图片压缩成功后 继续 回调 压缩函数。 以到达循环压缩图片的功能。
function app_img(rem, callback) {
	let that = this
	let index = rem.tempFiles[0].path.lastIndexOf("."); //获取图片地址最后一个点的位置  
	let img_type = rem.tempFiles[0].path.substring(index + 1, rem.tempFiles[0].path.length); //截取图片类型如png jpg
	let img_yuanshi = rem.tempFiles[0].path.substring(0, index); //截取图片原始路径
	let d2 = new Date().getTime(); //时间戳
	//压缩图片
	plus.zip.compressImage({
			src: rem.tempFiles[0].path, //你要压缩的图片地址
			dst: img_yuanshi + d2 + '.' + img_type, //压缩之后的图片地址(注意压缩之后的路径最好和原生路径的位置一样，不然真机上报code-5)
			quality: 10 //[10-100]
		},
		function(e) {
			console.log("Compress success!", e.target);
			//压缩之后路径转base64位的
			//通过URL参数获取目录对象或文件对象
			plus.io.resolveLocalFileSystemURL(e.target, function(entry) {
				// 可通过entry对象操作test.html文件 
				entry.file(function(file) { //获取文件数据对象
					var fileReader = new plus.io.FileReader(); // 文件系统中的读取文件对象，用于获取文件的内容
					//alert("getFile:" + JSON.stringify(file));
					fileReader.readAsDataURL(file); //以URL编码格式读取文件数据内容
					fileReader.onloadend = function(evt) { //读取文件成功完成的回调函数
						callback(evt.target.result);
					}
				})
			})
		},
		function(error) {
			console.log("Compress error!");
			console.log(JSON.stringify(error));
		}
	);
}

//微信压缩
function weixin_img(rem, callback) {
	let that = this
	wx.getImageInfo({ //获取这个图片 图片压缩
		src: rem.tempFiles[0].path, //需要获取的图片 图片选择不用我说了吧
		success: function(res) {
			var ctx = wx.createCanvasContext('attendCanvasId'); //使用一个canvas
			var canvasWidth = res.width //原图宽度 
			var canvasHeight = res.height; //原图高度
			var ratio = 2;
			// 保证宽高均在200以内
			while (canvasWidth > 200 || canvasHeight > 200) {
				//比例取整
				canvasWidth = Math.trunc(res.width / ratio)
				canvasHeight = Math.trunc(res.height / ratio)
				ratio++;
			}
			//绘制新图
			ctx.drawImage(rem.tempFiles[0].path, 0, 0, canvasWidth, canvasHeight)
			ctx.draw(false, () => {
				//获取图像数据， API 1.9.0
				wx.canvasGetImageData({
					canvasId: 'attendCanvasId',
					x: 0,
					y: 0,
					width: canvasWidth,
					height: canvasHeight,
					success: (res) => {
						let platform = wx.getSystemInfoSync().platform
						if (platform == 'ios') {
							// 兼容处理：ios获取的图片上下颠倒
							res = that.reverseImgData(res)
						}
						// 3. png编码
						let pngData = upng.encode([res.data.buffer], canvasWidth, canvasHeight)
						// 4. base64编码
						let base64 = wx.arrayBufferToBase64(pngData)
						// console.log('1111','data:image/jpeg;base64,'+base64)
						callback('data:image/jpeg;base64,' + base64);

					}
				})
			})
		},
	})
}

function h5_img(res, obj, callback) {
	var img = new Image();
	img.src = res.tempFiles[0].path;
	img.onload = function() {
		var that = this;
		// 默认按比例压缩
		var w = that.width,
			h = that.height,
			scale = w / h;
		w = obj.width || w;
		h = obj.height || (w / scale);

		//生成canvas
		var canvas = document.createElement('canvas'),
			ctx = canvas.getContext('2d');
		canvas.width = w;
		canvas.height = h;
		ctx.drawImage(that, 0, 0, w, h);

		// 默认图片质量为0.7
		var quality = 0.7;
		if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
			quality = obj.quality;
		}

		// 回调函数返回base64的值
		var base64 = canvas.toDataURL('image/jpeg', quality);
		callback(base64);
	}
}

function getParameter() {
   const url = location.search; //获取url中"?"符后的字串
   var theRequest = new Object();
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      var strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
      }
   }
   return theRequest;
}
// 兼容处理：ios获取的图片上下颠倒
function reverseImgData(res) {
	var w = res.width
	var h = res.height
	let con = 0
	for (var i = 0; i < h / 2; i++) {
		for (var j = 0; j < w * 4; j++) {
			con = res.data[i * w * 4 + j]
			res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j]
			res.data[(h - i - 1) * w * 4 + j] = con
		}
	}
	return res
}

function isEmpyt(res) {
	return typeof res == 'undefined' || res == ''
}

function isNotEmpyt(res) {
	return typeof res != 'undefined' || res != ''
}

function isFillInfo(userInfo) {
	return userInfo != null && isNotEmpyt(userInfo.AAC003) && isNotEmpyt(userInfo.AAC002) && isNotEmpyt(userInfo.AKC803) && isNotEmpyt(
		userInfo.AAE140)
}

export {
	h5_img,
	app_img,
	weixin_img,
	deepCopy,
	sys,
	timeToDate,
	formatMoney,
	successToShow,
	throttle,
	errorToShow,
	time2date,
	getParameter,
	isPhoneNumber,
	isIdCardNumber,
	isInArray,
	loadToShow,
	loadToHide,
	navigateTo,
	redirectTo,
	modelShow,
	builderUrlParams,
	isWeiXinBrowser,
	getDate,
	dateformat,
	isFillInfo,
	isEmpyt,
	Encrypt,
	Decrypt
}
